import RTLog from './log';

function errorMessageReadable(msg) {
    // 错误信息优化
    msg = msg || '未知错误';

    try {
        // 删除微信小程序框架底层堆栈日志
        msg = msg.split('\n').filter(
            line => {
                return (/.*WA\w*(Service|Context)\.js:2:/.test(line) === false);
            }
        ).join('\n');

        const knownErrors = [
            {
                'reg': /.*(ERR_ADDRESS_UNREACHABLE|ERR_INTERNET_DISCONNECTED)$/,
                'content': msg => { return '网络错误，请检查您手机网络是否正常'; }
            },
            {
                'reg': /.*(请求超时|timeout)$/,
                'content': msg => { return '请求超时，请检查您手机网络是否正常'; }
            },
            {
                // navigateTo:fail page "pages/orders2/orders" is not found
                'reg': /.*:fail page \"[\w\/]+\" is not found$/,
                'content': msg => {
                    let page = msg.split('fail page ')[1].split(' ')[0];
                    return '页面不存在: ' + page.replace(/\"/g, '');
                }
            }
        ];

        console.log(msg);
        for (let i = 0; i < knownErrors.length; ++i) {
            if (knownErrors[i].reg.test(msg)) {
                msg = knownErrors[i].content(msg);
                break;
            }
        }
    } catch (e) {
        console.error(e);
    }

    return msg;
}

function onError(msg) {
    msg = msg || '未知错误';
    msg = errorMessageReadable(msg);
    const skiped_errors = [
        /:toast can't be found$/,
        /.*showLoading.*/,
        /.*updateTextView:fail.*/,
        /.*insertTextView:fail.*/,
        /.*insertImageView:fail.*/,
        /.*updateImageView:fail.*/,
        /.*removeTextView:fail.*/,
        /.*removeImageView:fail.*/,
    ];

    for (let i = 0; i < skiped_errors.length; ++i) {
        if (skiped_errors[i].test(msg)) {
            return;
        }
    }

    wx.showModal({
        title: 'o(╥﹏╥)o',
        content: msg,
        showCancel: false,
        confirmText: '知道了',
        success: () => {
            wx.reLaunch({
                url: '/pages/index/index',
                success: () => {
                    console.log('relaunch success');
                },
                fail: err => {
                    console.error('relaunch fail! err:', err);
                }
            });
        }
    });
    RTLog.error('onError: ', msg);
}

function onUnhandledRejection(evt) {
    onError((evt && evt.reason) ? evt.reason.errMsg : 'UnhandledRejection Error');
}


module.exports = {
    onError,
    onUnhandledRejection
};
